package com.cari.oa.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.cari.oa.domain.SysModuleEntity;
import com.cari.oa.service.SysModuleService;
import com.cari.oa.util.Contants;
import com.cari.oa.util.StrUtils;
import com.cari.oa.util.Utils;

/**
 * 系统模块controller
 * User: yexuhui
 * Date: 12-12-19
 * Time: 上午10:46
 */
@Controller
@SessionAttributes("username")
public class SysModuleController {

    @Resource
    private SysModuleService sysModuleService;
    
    public static final String MODULE_NAME = "SYS_MODULE_MANAGE";

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(df, false));
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    }

    @RequestMapping("/system/module/list.do")
    public String list(String enname, String alias, String parentId, Integer curPage, ModelMap modelMap) {
        if(curPage == null) curPage = 1;
        long totalRecords = sysModuleService.getCount(enname, alias, parentId);
        long totalPage = totalRecords / Contants.PAGE_SIZE + (totalRecords % Contants.PAGE_SIZE != 0 ? 1 : 0);
        
        List<SysModuleEntity> moduleList = sysModuleService.getPage(enname, alias, parentId, curPage, Contants.PAGE_SIZE);
        List<SysModuleEntity> pModuleList = sysModuleService.getAllTopModules();

        Map<String, String> pNameMap = new HashMap<String, String>();
        for (SysModuleEntity moduleEntity : pModuleList) {
            pNameMap.put(moduleEntity.getId(), moduleEntity.getAlias());
        }

        modelMap.addAttribute("moduleList", moduleList);
        modelMap.addAttribute("pModuleList", pModuleList);
        modelMap.addAttribute("pNameMap", pNameMap);
        modelMap.addAttribute("curPage", curPage);
        modelMap.addAttribute("totalPage", totalPage);
        modelMap.addAttribute("totalRecords", totalRecords);

        modelMap.addAttribute("enname", enname);
        modelMap.addAttribute("alias", alias);
        modelMap.addAttribute("parentId", parentId);

        return "system/module/list";
    }

    @RequestMapping(value = "/system/module/insert.do", method = RequestMethod.GET)
    public String enterInsert(String qs, ModelMap modelMap) {
        List<SysModuleEntity> pModuleList = sysModuleService.getAllTopModules();
        modelMap.addAttribute("pModuleList", pModuleList);
        modelMap.addAttribute("qs", qs);
        return "system/module/insert";
    }

    @RequestMapping(value = "/system/module/view.do", method = RequestMethod.GET)
    public String enterView(String id, ModelMap modelMap) {
        SysModuleEntity module = sysModuleService.getById(id);
        if(StrUtils.isNotEmpty(module.getParentId())) {
            SysModuleEntity pModule = sysModuleService.getById(module.getParentId());
            modelMap.addAttribute("parentAlias", pModule.getAlias());
        }
        modelMap.addAttribute("module", module);
        return "system/module/view";
    }

    @RequestMapping(value = "/system/module/edit.do", method = RequestMethod.GET)
    public String enterEdit(String id, String qs, ModelMap modelMap) {
        List<SysModuleEntity> pModuleList = sysModuleService.getAllTopModules();
        SysModuleEntity module = sysModuleService.getById(id);
        modelMap.addAttribute("module", module);
        modelMap.addAttribute("pModuleList", pModuleList);
        modelMap.addAttribute("qs", qs);
        return "system/module/edit";
    }

    @RequestMapping(value = "/system/module/insert.do", method = RequestMethod.POST)
    @ResponseBody
    public String postInsert(@ModelAttribute("username") String username, 
    		@Valid SysModuleEntity sysModuleEntity, BindingResult result) {
        if(result.hasFieldErrors())
            return Utils.errorJsonResp(result.getFieldError().getDefaultMessage());

        if (sysModuleService.existByEnname(sysModuleEntity.getEnname()))
            return Utils.errorJsonResp("系统模块英文名已存在");

        sysModuleService.insert(sysModuleEntity);
        
        SysOperLogController.addOperLog(username, MODULE_NAME, "新增模块" + sysModuleEntity.getEnname());
        return Utils.normalJsonResp();
    }

    @RequestMapping(value = "/system/module/edit.do", method = RequestMethod.POST)
    @ResponseBody
    public String postEdit(@ModelAttribute("username") String username, 
    		@Valid SysModuleEntity sysModuleEntity, BindingResult result) {
        if(result.hasFieldErrors())
            return Utils.errorJsonResp(result.getFieldError().getDefaultMessage());

        sysModuleService.update(sysModuleEntity);
        
        SysOperLogController.addOperLog(username, MODULE_NAME, "修改模块" + sysModuleEntity.getEnname());
        return Utils.normalJsonResp();
    }

    @RequestMapping(value = "/system/module/delete.do")
    @ResponseBody
    public String postDelete(@ModelAttribute("username") String username, String id) {
        SysModuleEntity sysModuleEntity = sysModuleService.getById(id);
        if(sysModuleEntity == null) return Utils.errorJsonResp("该模块已不存在，请刷新页面");

        if(sysModuleService.isModuleUsedByRole(sysModuleEntity.getEnname()))
            return Utils.errorJsonResp("还有角色关联该系统模块，请先解除关联，才能删除");

        sysModuleService.delete(sysModuleEntity);
        
        SysOperLogController.addOperLog(username, MODULE_NAME, "删除模块" + sysModuleEntity.getEnname());
        return Utils.normalJsonResp();
    }
}
